package cn.txy.article.controller;

import cn.txy.article.mongo.Comment;
import cn.txy.article.query.CommentQuery;
import cn.txy.article.service.CommentService;
import cn.txy.config.R;
import cn.txy.system.annotation.PreAuthorize;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/comment")
public class CommentController {
    @Autowired
    private CommentService commentService;
    @Autowired
    private MongoTemplate mongoTemplate;
    @GetMapping("/article/{id}")
    @PreAuthorize(name = "查看课程信息",sn="permission:delAll",descs = "查看课程信息")
    public List<Comment> findByArticleId(@PathVariable("id") Long id){
        return commentService.findByArticleId(id);
    }

@PostMapping
@PreAuthorize(name = "查看课程信息",sn="permission:delAll",descs = "查看课程信息")
    public R save(@RequestBody Comment comment){
        comment.setCreateTime(new Date());
        comment.setState(1);
        commentService.save(comment);
        return R.ok();
    }

    @PreAuthorize(name = "删除课程信息",sn = "comment:delete",descs ="删除课程信息")
    @ApiOperation("删除课程信息")
    @DeleteMapping("/{articleId}")
    public R delete(@PathVariable("articleId") String id) {
        Query getId =  new Query(Criteria.where("id").is(id));
        this.mongoTemplate.remove(getId, Comment.class);
        return R.ok();
    }
    @PostMapping("/commentPage")
    public R page(@RequestBody CommentQuery commentQuery){
        Pageable pageable = PageRequest.of(commentQuery.getPage() - 1, commentQuery.getSize());
        Query query = new Query(Criteria.where("state").is(1));
        query.with(pageable);
        long total = mongoTemplate.count(query, Comment.class);
        java.util.List<Comment> comments = mongoTemplate.find(query, Comment.class);
        Page<Comment> commentPage = new PageImpl<>(comments, pageable, total);
        return R.ok(commentPage);
    }


}
